/**
 * Copyright @ 2019 HoldTime Inner Mongolia Co. Ltd.
 */
package com.holdtime.jtt809dataservice.server.processor;

import com.holdtime.common.utils.general.ApiResponseModel;
import com.holdtime.common.utils.general.BaseResultCode;
import com.holdtime.jtt809dataservice.business.api.LinkService;
import com.holdtime.jtt809dataservice.common.bean.MainLinkLogOutReqDTO;
import com.holdtime.jtt809dataservice.common.event.MessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.ProtocolProcessor;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.RawBody;
import protocol.jtt809.body.UpDisconnectReq;
import protocol.jtt809.body.UpDisconnectRsp;

import java.net.InetSocketAddress;

/**
 * 项目名称： jtt809gateway<br>
 * 功能描述： UpDisconnectReqProcessor概述：主链路注销请求消息处理<br>
 * 创  建 人： guoai<br>
 * 创建日期： 2019年7月26日<br>
 * 修  改 人：  <br>
 * 修改时间：<br>
 * 修改内容：<br>
 * 版      本： 1.0.0
 */
@Component
public @Slf4j class UpDisconnectReqProcessor implements ProtocolProcessor {

    @Resource
    private ProtocolJT809 protocolJT809;
    @Resource
    private LinkService linkService;

    @Override
    public int getMsgID() {
        return UpDisconnectReq.MSG_ID;
    }

    @Override
    public void process(MessageReceiveEvent event) {
        JTT809Packet<RawBody> source = event.getSource();
        RawBody body = source.getBody();
        UpDisconnectReq req = new UpDisconnectReq();
        req.from(body.getRaw());
        ChannelHandlerContext session = event.getChannelHandlerContext();

        try {
            MainLinkLogOutReqDTO mainLinkLogOutReqDTO = new MainLinkLogOutReqDTO();
            InetSocketAddress inetSocketAddress = (InetSocketAddress) session.channel().remoteAddress();
            String ip = inetSocketAddress.getAddress().getHostAddress();
            mainLinkLogOutReqDTO.setIp(ip);
            mainLinkLogOutReqDTO.setUseId(req.getUserid());
            mainLinkLogOutReqDTO.setPassword(req.getPassword());
            ApiResponseModel<?> model = linkService.dealMainLinkLogOutReq(mainLinkLogOutReqDTO);
            if (model.getResultCode() == BaseResultCode.SUCCESS.getCode()) {
                UpDisconnectRsp rsp = new UpDisconnectRsp();
                JTT809Packet<UpDisconnectRsp> packet = protocolJT809.getPacket(rsp, UpDisconnectRsp.MSG_ID, source.getMsgGnsscenterid());
                session.write(packet);
            } else {
                log.error("主链路注销请求处理失败：", model.getMsg());
            }
        } catch (Exception e) {
            log.error("主链路注销请求处理异常：", e);
        }
    }

}
